import Cookie from 'js-cookie'
import { localStorage, sessionStorage } from '~/plugins/tools'

const state = {
    userInfo: null
}

const mutations = {
    SET_USERINFO: (state, userInfo) => {
        state.userInfo = userInfo
        if (userInfo) {
            localStorage.setItem('userInfo', userInfo)
            Cookie.set('companyId', userInfo.companyId)
            Cookie.set('departmentId', userInfo.departmentId)
            Cookie.set('orgCategoryId', userInfo.orgCategoryId)
            Cookie.set('token', userInfo.token)
        }
    }
}

const actions = {
    setUserInfo ({ commit }, data) {
        return new Promise((resolve) => {
            commit('SET_USERINFO', data)
            resolve()
        })
    },
    logout ({ dispatch }) {
        dispatch('setUserInfo', null)
        localStorage.removeItem('ALL')
        sessionStorage.removeItem('ALL')
        if (process.client) {
            Cookie.remove('companyId')
            Cookie.remove('departmentId')
            Cookie.remove('orgCategoryId')
            Cookie.remove('token')
            window.location.href = '/auth/login'
        }
    },
    nuxtServerInit ({ commit, store }, { req }) {
        // 切分Cookie
        const cookie = req.headers.cookie.split(';')
        const userInfo = {}

        // 遍历Cookie，取得需要的值
        cookie.forEach((e) => {
            const key = e.split('=')[0].replace(/(^\s*)|(\s*$)/g, '')
            userInfo[key] = e.split(key + '=')[1]
            if (e.split(key + '=')[1] === 'null') {
                userInfo[key] = null
            }
        })

        commit('SET_USERINFO', {
            ...(state.userInfo || {}),
            ...userInfo
        })
    },
    initStore ({ commit }) {
        if (process.client) {
            commit('SET_USERINFO', localStorage.getItem('userInfo'))
        }
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
